package com.study.compose.coroutines.dispatchers

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.coroutines.*

/**
 * 定义一个，协程的回调类
 */
class MyContinuation(override val context: CoroutineContext = Dispatchers.Unconfined) :
    Continuation<String> {
    /**
     * 挂起函数恢复执行的方法，线程切换回调方法
     */
    override fun resumeWith(result: Result<String>) {
        log("resumeWith运行结果：${result.getOrNull()}")
    }
}

/**
 * 创建一个自定义线程的挂起函数
 */
suspend fun test() = suspendCoroutine<String> {
    thread(name = "自定义线程") {
        TimeUnit.SECONDS.sleep(1)
        log("调用resume方法")
        it.resume("hello")
    }
}

fun main() = runBlocking {
    Thread.currentThread().name = "主线程"

    //定义一个挂起函数
    val suspendFun = suspend {
        log("运行前")
        val result = test()
        log("运行后${result}")
        result
    }


    //初始化线程切换回调类
    val myContinuation = MyContinuation()

    //开始执行挂起函数
    suspendFun.createCoroutine(myContinuation)
    val result = suspendFun()

    log("执行结果回调${result}")

    TimeUnit.SECONDS.sleep(10000)
}

fun log(log: String) {
    println("${Thread.currentThread().name}:${log}")
}